package com.anssy.voteballot.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.core.app.ActivityCompat;

import java.util.List;
import java.util.Random;

/**
 * Android手机系统的一些通用方法。
 *
 * @author TMH
 */
public class ADKSystemUtils {


    /**
     * 利用NotificationManager播放默认铃声 ，重复响铃
     * 但是应用程序在后台运行时，就无法弹出dialog
     *
     * @param context
     * @return Notification id
     */
    public static int playSound4Notification(Context context, boolean isLooper) {
        Log.e("AlarmRingService", "ring...");
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification();
        notification.defaults = Notification.DEFAULT_SOUND;
        if (isLooper)
            notification.flags |= Notification.FLAG_INSISTENT;    //重复响铃
        else
            notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;    //响铃一次？
        int soundId = new Random(System.currentTimeMillis()).nextInt(Integer.MAX_VALUE);
        notificationManager.notify(soundId, notification);

        return soundId;
    }


    /**
     * @param applicationContext
     * @param isLooping          是否重复响铃
     */
    public static void playSound4MediaPlayer(Context applicationContext, boolean isLooping) {
        //int soundId = new Random(System.currentTimeMillis()).nextInt(Integer.MAX_VALUE);
        //mediaPlayer = MediaPlayer.create(getApplicationContext(), soundId);

        Uri ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(applicationContext, RingtoneManager.TYPE_RINGTONE);
        MediaPlayer mediaPlayer = MediaPlayer.create(applicationContext, ringtoneUri);

        //mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.passed);
        mediaPlayer.setLooping(isLooping);
        mediaPlayer.start();
    }


    public static boolean isPhoneNumber(String phoneNumber) {
        int length = phoneNumber.length();

        if (length != 11)
            return false;

        char charAt = phoneNumber.charAt(0);
        if (charAt != '1')
            return false;

        try {
            Long.parseLong(phoneNumber);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }


    public static void callNumberDIAL(Context context, String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNumber);
        intent.setData(data);
        context.startActivity(intent);
    }


    @SuppressLint("MissingPermission")
    public static void callNumberCALL(Context context, String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + phoneNumber);
        intent.setData(data);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        context.startActivity(intent);
    }


    /**
     * 判断当前应用程序处于前台还是后台
     *
     * @param context
     * @return true 在后台，false在前台
     */
    public static boolean isApplicationRunToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }


    /**
     * 检查是否有存储卡
     *
     * @return
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 检测软件是否在系统中安装
     *
     * @param context
     * @param packageName 软件的包名
     * @return 安装了返回true，否则返回false
     */
    public static boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager()
                    .getApplicationInfo(packageName,
                            PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (NameNotFoundException e) {
            return false;
        }
    }


    /**
     * 获取软件的内部版本号
     *
     * @param context
     * @return 错误返回-1
     */
    public static int getVersionCode(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }


    /**
     * 获取软件的外部版本号
     *
     * @param context
     * @return 错误返回null
     */
    public static String getVersionName(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 通过app的名称得到app的主activity名或包名
     *
     * @param launchName launch页面上的软件名称
     * @param type       通过type类型确定最后得到的字符串类型 {@link AppNameType}
     * @param context
     * @return
     */
    public static String getPackageNameOrMainActivityName(String launchName, AppNameType type,
                                                          Context context) {

        PackageManager mPackageManager = context.getPackageManager();
        List<ResolveInfo> mAllApps;

        String tempstr = null;
        String result = null;

        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        mAllApps = mPackageManager.queryIntentActivities(mainIntent, 0);

        for (int i = 0; i < mAllApps.size(); i++) {
            ResolveInfo info = mAllApps.get(i);
            tempstr = info.loadLabel(mPackageManager).toString();
            if (tempstr.equals(launchName)) {
                switch (type) {
                    case packageName:
                        result = info.activityInfo.packageName;     // 得到包名
                        break;
                    case activityName:
                        result = info.activityInfo.name;        // 得到主activity名
                        break;
                }
            }
        }
        return result;

    }


    /**
     * 判断应用程序是否在运行
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean appIsRun(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = am.getRunningTasks(100);
        for (RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(packageName) && info.baseActivity.getPackageName().equals(packageName)) {
                return true;
            }
        }
        return false;
    }


    public static void openService(Context context, String packageName, String serviceClassName) {
        Intent intent = new Intent();
        intent.setClassName(packageName, serviceClassName);
        intent.setAction("android.intent.action.VIEW");
        context.startService(intent);
    }


    /**
     * 获取应用程序包名
     *
     * @param context
     * @return
     */
    public static String getAppPackageName(Context context) {
        String packageName = context.getApplicationContext().getPackageName();
        return packageName;
    }


    /**
     * 获取屏幕分辨率
     *
     * @param activity
     * @return
     */
    public static DisplayMetrics getScreenSize(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        //Log.d(TAG, dm.widthPixels + "*" + dm.heightPixels);
        //Log.d(TAG, dm.density + " :: " + dm.densityDpi);
        return dm;
    }


    public static int dip2px(Context context, float dipValue) {
		/*
        final float scale = context.getResources().getDisplayMetrics().density;   
        return (int)(dipValue * scale + 0.5f);   
        */
        final float scale = context.getResources().getDisplayMetrics().densityDpi;
        return (int) (dipValue * (scale / 160) + 0.5f);
    }


    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    /**
     * 关闭软键盘
     *
     * @param activity
     */
    public static void hideKeyboard(Activity activity) {
        InputMethodManager manager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        ;
        if (activity.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (activity.getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    /**
     * 显示/隐藏软键盘
     * 输入法在窗口上切换显示，如果输入法在窗口上已经显示，则隐藏，如果隐藏，则显示输入法到窗口上
     *
     * @param context
     */
    public static void showKeyboard(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }


    public static int getKeyboardHeight(View root) {
        Rect r = new Rect();
        root.getWindowVisibleDisplayFrame(r);

        int screenHeight = root.getRootView().getHeight();
        int heightDifference = screenHeight - (r.bottom - r.top);
        //Log.e("Keyboard Size", "键盘高度   Size: " + heightDifference);

        return heightDifference;
    }


    public static boolean isKeyBoardShow(Activity activity) {
        return activity.getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED;
    }


    private enum AppNameType {

        /**
         * 应用程序包名
         */
        packageName,

        /**
         * 应用程序主Activity名
         */
        activityName
    }

}
